const puppeteer = require('puppeteer');

async function main() {
    try {
        // 获取当前用户名
        const username = process.env.USER || process.env.USERNAME;
        
        // 根据操作系统设置正确的用户数据目录
        const userDataDir = process.platform === 'win32'
            ? `C:\\Users\\${username}\\AppData\\Local\\Google\\Chrome\\User Data`  // Windows
            : `/Users/${username}/Library/Application Support/Google/Chrome`;  // macOS

        // 启动浏览器
        const browser = await puppeteer.launch({
            headless: false,  // 设置为false可以看到浏览器界面
            defaultViewport: null,
            channel: 'chrome',  // 使用本地Chrome
            executablePath: process.platform === 'win32' 
                ? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'  // Windows路径
                : '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // macOS路径
            userDataDir: userDataDir,
            args: [
                '--profile-directory=Profile 9',
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--no-first-run',
                '--no-single-process',
                '--disable-gpu'
            ]
        });

        // 创建新页面
        const page = await browser.newPage();
        page.setViewport({width: 800, height: 600})

        // 访问 Hacker News Ask 页面
        await page.goto('https://news.ycombinator.com/ask');
        await new Promise(resolve => setTimeout(resolve, 3000));

        // 点击登录链接
        await page.click('a[href^="login"]');
        await new Promise(resolve => setTimeout(resolve, 3000));
        // 输入用户名
        await page.type('input[name="acct"]', 'summizeralert');
        await new Promise(resolve => setTimeout(resolve, 1000));

        // 输入密码 
        await page.type('input[name="pw"]', 'cTst@-1BySumerAl');
        await new Promise(resolve => setTimeout(resolve, 1000));
        // 等待登录按钮加载并点击
        await page.click('input[type="submit"][value="login"]');
        await new Promise(resolve => setTimeout(resolve, 3000));

        // 等待文章列表加载并点击第四个文章
        const articles = await page.$$('.athing');
        if (articles.length >= 4) {
            await articles[3].click();
        }

        // 等待3秒确保操作完成
        await new Promise(resolve => setTimeout(resolve, 3000));

        // 截图
        await page.screenshot({ path: 'screenshot.png' });

        // 关闭浏览器
        await browser.close();
    } catch (error) {
        console.error('测试过程中发生错误:', error);
    }
}

main();
